package com.dgut.service;

import com.dgut.entity.Administrator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class CustomUserDetailService implements UserDetailsService {

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    AdminService adminService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("执行自定义登录逻辑");
        System.out.println("请求认证的用户名：" + username);
        Administrator administrator = adminService.getAdministratorByAccount(username);

        //1.根据用户名去数据库查询，如果不存在则抛UsernameNotFoundException异常
        //if(!administrator.getAccount().equalsIgnoreCase(username)) {    //数据库账号
        if(!"2021010101011".equals(username)){
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        //2.比较密码(注册时存到数据库的密码已经加密)，如果匹配成功返回UserDetails
        //String password = passwordEncoder.encode(administrator.getPassword());
        String  password = passwordEncoder.encode("123456");
        return new User(username, password, AuthorityUtils.commaSeparatedStringToAuthorityList("ADMIN"));
    }


}
